<template>
  <div class="course wrap">
    <h1>全部课程</h1>
    <!-- 课程分类TAB切换 -->
    <el-row class="cate">
      <b>课程分类</b>
      <el-button
        :type="activeIndex == index ? 'primary' : ''"
        plain
        size="small"
        :text="activeIndex != index ? true : false"
        v-for="(item, index) in oneCateList"
        :key="item.id"
        @click="clickCate(1, index, item.id)"
        >{{ item.title }}</el-button
      >
    </el-row>
    <el-row class="cate two-cate">
      <el-button
        :type="activeIndex2 == index ? 'primary' : ''"
        plain
        size="small"
        :text="activeIndex2 != index ? true : false"
        v-for="(item, index) in twoCateList"
        :key="item.id"
        @click="clickCate(2, index, item.id)"
        >{{ item.title }}</el-button
      >
    </el-row>
    <!-- 课程分类排序 -->
    <el-row class="cate-sort">
      <el-button
        :type="activeIndexSort == index ? 'success' : ''"
        :text="activeIndexSort != index ? true : false"
        v-for="(item, index) in cateSort"
        :key="item.id"
        @click="clickTabSort(index)"
      >
        {{ item.name }}
        <el-icon>
          <Bottom v-show="!sortBoolean && activeIndexSort == index" />
          <Top v-show="sortBoolean && activeIndexSort == index" />
        </el-icon>
      </el-button>
    </el-row>
    <!-- 课程列表 -->
    <el-row :gutter="20">
      <el-col :span="6" v-for="item in courseList" :key="item.id">
        <el-card @click="toCourseDetail(item.id, item.teacherId)">
          <template #header>
            <img :src="item.cover" style="width: 100%; height: 200px" />
          </template>
          <div class="card-content">
            <h3>{{ item.title }}</h3>
            <div class="content-bottom">
              <div>
                <span>{{ item.buyCount }}人学习</span>
                <span> | </span>
                <span>{{ item.viewCount }}人浏览</span>
              </div>
              <el-tag type="success">￥{{ item.price }}</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 分页器 -->
    <div style="margin-top: 20px; " class="page">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="currentPage4"
            v-model:page-size="pageSize4"
            :page-sizes="[8, 16, 24, 32]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="getList"
            @current-change="getList"
          >
          </el-pagination>
        </el-config-provider>
      </div>
      </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router"
import axios from "../../assets/js/axios";
import zhCn from "element-plus/es/locale/lang/zh-cn";
const router = useRouter()
const total = ref(0)
// 选中的分类标识
const activeIndex = ref(0);
const activeIndex2 = ref(0);
const activeIndexSort = ref(0);
const sortBoolean = ref<any>(null);
const subjectId = ref<any>();
const subjectParentId = ref<any>();

// 点击课程详情

// 点击选中的分类按钮
const clickCate = (level: number, index: number, id: number) => {
  if (level == 1) {
    activeIndex.value = index;
    subjectParentId.value = id;
    if (id != 0) {
      // 请求二级分类接口
      axios
        .get("/serviceedu/edu-subject/getTwoSubjectsByParentId/"+id, {})
        .then((res: any) => {
          //二级分类列表
          twoCateList.value = [{ id: 0, title: "全部" }];
          twoCateList.value = twoCateList.value.concat(res.data.list);
        });
    } else {
      twoCateList.value = [{ id: 0, title: "全部" }];
    }
  } else {
    activeIndex2.value = index;
    subjectId.value = id;
  }
  if (id === 0) {
    subjectParentId.value = null;
    subjectId.value = null;
  }
  getCourseList();
};

// 点击分类排序
const clickTabSort = (index: number) => {
  if (activeIndexSort.value !== index) {
    sortBoolean.value = false;
    activeIndexSort.value = index;
  } else {
    sortBoolean.value = !sortBoolean.value;
  }

  // 排序字段和顺序
  let sortField = '';
  let sortOrder = sortBoolean.value ? 'asc' : 'desc';

  if (index === 0) {
    sortField = 'view_count';
  } else if (index === 1) {
    sortField = 'gmt_create';
  } else if (index === 2) {
    sortField = 'price';
  }

  getCourseList(sortField, sortOrder);
};

const oneCateList = ref<any>([]);
const twoCateList = ref<any>([
  {
    id: 0,
    title: "全部",
  },
]);

const cateSort = ref([
  {
    id: 1,
    name: "浏览量",
  },
  {
    id: 2,
    name: "最新",
  },
  {
    id: 3,
    name: "价格",
  },
]);

// 分页器
const currentPage4 = ref(1);
const pageSize4 = ref(8);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);

const courseList = ref<any>([]);

// 获取课程列表
const getCourseList = (sortField?: string, sortOrder?: string) => {
  // 发送课程列表请求
  axios
    .get("/serviceedu/edu-course/getCourseCondition", {
        page: currentPage4.value,
        size: pageSize4.value,
        subjectParentId: subjectParentId.value,
        subjectId: subjectId.value,
        sortField: sortField, // 排序字段
        sortOrder: sortOrder, // 排序顺序 (asc 或 desc)
    })
    .then((res: any) => {
      // 课程列表
      courseList.value = res.data.list;
      total.value = res.data.total;
    });
};
//获取列表
const getList = () => {
  //获取课程一级分类
  axios.get("/serviceedu/edu-subject/getAllSubject", {}).then((res: any) => {
    //一级分类列表
    res.data.list.unshift({ id: 0, title: "全部" });
    oneCateList.value = res.data.list;
  });
  // 调用课程列表
  getCourseList();
};
getList();
const toCourseDetail = (id: number, teacherId: number) => {
  // 发送请求到后端，更新浏览量
  axios.post(`/serviceedu/edu-course/updateViewCount/${id}`,{})
    .then(() => {
      console.log("浏览量更新成功");
      // 跳转到课程详情页
      router.push({ path: '/courseDetail', query: { id: id, teacherId: teacherId } });
    })
    .catch(err => {
      console.error("更新浏览量失败", err);
    });

  // 更新前端显示的浏览量
  const course = courseList.value.find((course: any) => course.id === id);
  if (course) {
    course.viewCount += 1; // 前端手动增加浏览量
  }
};
</script>

<style lang="less" scoped>
.course {
  h1 {
    margin: 20px 0;
  }
  .cate {
    border-top: 1px solid #f2f2f2;
    border-bottom: 1px solid #f2f2f2;
    padding: 10px;
    b {
      color: #cccccc;
      margin-right: 20px;
    }
    .el-button {
    border-radius: 8px;
    }
  }
  .two-cate {
    padding-left: 90px;
    border: none;
  }
  .cate-sort {
    background-color: #f2f2f2;
    margin: 20px 0;
  }
  .el-card {
    margin-bottom: 20px;
    h3 {
      font-size: 20px;
    }
    .content-bottom {
      display: flex;
      justify-content: space-between;
      span {
        font-size: 14px;
        color: #cccccc;
      }
    }
  }

  .el-pagination {
    justify-content: center;
    margin: 30px 0;
  }
}
</style>
